﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace FormView.UI.PromptView
{
	public class PromptComboBoxView : IPromptViewControl
	{
		public static readonly string TagName = "combobox";

		public object GetValue(FrameworkElement element)
		{
			Grid grid = element as Grid;
			ComboBox comboBox = grid.Children[1] as ComboBox;
			return comboBox.SelectedIndex;
		}

		public FrameworkElement GetElement(PromptFormWindow win, string tipText, object value)
		{
			string[] items = ParseSelectItems(ref tipText);
			if (items.Length <= 0)
			{
				throw new ArgumentException("Prompt combobox组件至少需要一个选项");
			}
			int defaultIndex = 0;
			if (value != null)
			{
				if (!int.TryParse(value.ToString(), out defaultIndex))
				{
					throw new ArgumentException("Prompt combobox组件的默认值应为选项的索引");
				}
			}

			if (defaultIndex < 0 || defaultIndex >= items.Length)
			{
				throw new ArgumentException("Prompt combobox组件的默认值不可超出选项的索引范围");
			}

			Grid grid = new Grid();
			grid.Background = PromptFormWindow.DefaultBgColor;
			grid.RowDefinitions.Add(new RowDefinition());
			grid.ColumnDefinitions.Add(new ColumnDefinition(){Width = GridLength.Auto});
			grid.ColumnDefinitions.Add(new ColumnDefinition(){Width = new GridLength(1, GridUnitType.Star) });

			TextBlock textBlock = new TextBlock()
			{
				Padding = new Thickness(2),
				Foreground = PromptFormWindow.DefaultForeColor,
				Text = tipText,
				TextAlignment = TextAlignment.Center
			};
			Grid.SetColumn(textBlock, 0);
			grid.Children.Add(textBlock);

			ComboBox comboBox = new ComboBox()
			{
				Style = win.Resources["ComboBoxStyle"] as Style,
				Foreground = PromptFormWindow.DefaultForeColor,
				Background = new SolidColorBrush(Colors.Transparent),
				Padding = new Thickness(5, 2, 0, 5)
			};
			foreach (var item in items)
			{
				comboBox.Items.Add(item);
			}
			Grid.SetColumn(comboBox, 1);
			comboBox.SelectedIndex = defaultIndex;
			grid.Children.Add(comboBox);

			return grid;
		}

		private string[] ParseSelectItems(ref string tipText)
		{
			Regex regex = new Regex(@"\[(.*)]");
			Match match = regex.Match(tipText);
			if (!match.Success)
			{
				return new string[0];
			}
			tipText = tipText.Split('[')[0].Trim();

			return match.Groups[1].Value.Split(';')
				.Where(val => !string.IsNullOrWhiteSpace(val))
				.Select(val => val.Trim())
				.ToArray();
		}

		public void OnRenderView(PromptFormWindow promptWindow, FrameworkElement element)
		{
			// ignore
		}
	}
}
